package com.gome.gop.common;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApiUtil {
    
    public final static String DEFAULT_CHARSET = "utf-8";
    
    protected static final Logger logger = LoggerFactory.getLogger(ApiUtil.class);
    
    /*
     * 得到返回的内宿
     */
    public static String getResult(String urlStr, String content) {
        URL url = null;
        HttpURLConnection connection = null;
        String result = null;
        
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setRequestProperty("Accept-Encoding", "gzip");
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(content);
            out.flush();
            out.close();
            
            String encoding = connection.getContentEncoding();
            InputStream inputStream = connection.getInputStream();
            InputStreamReader is = null;
            BufferedReader reader = null;
            if ("gzip".equals(encoding)) {
                is = new InputStreamReader(new GZIPInputStream(inputStream), "UTF-8");
                reader = new BufferedReader(is);
            }
            else {
                is = new InputStreamReader(inputStream, "UTF-8");
                reader = new BufferedReader(is);
            }
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                reader.close();
                result = buffer.toString();
            }
            else {
                System.out.println("url:" + urlStr + ",ResponseCode:" + connection.getResponseCode() + ",ResponseMessage:" + connection.getResponseMessage());
            }
        }
        catch (IOException e) {
            logger.warn("网络连接错误： "+urlStr);
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
    
    /*
     * 组装请求参数，返回怤غkey1=value1&key2=value2形式
     */
    public static String createRequestParam(Map<String, Object> map) {
        StringBuilder param = new StringBuilder();
        
        for (Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Object> e = it.next();
            Object value = e.getValue();
            if (value != null) {
                try {
                    value = URLEncoder.encode(value.toString(), DEFAULT_CHARSET);
                }
                catch (UnsupportedEncodingException ex) {
                }
                param.append("&").append(e.getKey()).append("=").append(value);
            }
        }
        return param.toString().substring(1);
    }
    
    /*
     * 签名方法，用于生成签名㿊 *
     * 
     * @param params 传给服务器的参数
     * 
     * @param secret 分配给您的APP_SECRET
     */
    public static String sign(Map<String, Object> params, String secret) {
        String result = null;
        if (params == null)
            return result;
        
        // 将参数按key排序
        Set<String> keys = params.keySet();
        String[] ps = new String[keys.size()];
        int i = 0;
        for (String key : keys) {
            Object value = params.get(key);
            if (value != null) {
                ps[i++] = key + value.toString();
            }
        }
        if (i == 0)
            return result;
        String[] ss = new String[i];
        System.arraycopy(ps, 0, ss, 0, i);
        Arrays.sort(ss);
        
        // 将secret同时放在头尾，拼成字符串
        StringBuilder orgin = new StringBuilder(secret);
        for (int j = 0; j < ss.length; j++) {
            orgin.append(ss[j]);
        }
        orgin.append(secret);
        
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
        }
        catch (Exception ex) {
            throw new RuntimeException("sign error !");
        }
        return result;
    }
    
    /*
     * 二行制转字符丿
     */
    private static String byte2hex(byte[] b) {
        
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
    
}
